<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getAccessToken, getUserInfo } from '../utils/auth.js'

const router = useRouter()

// 消息列表
const messages = ref([])

// 输入框内容
const inputText = ref('')
const inputHeight = ref(48)

// 是否正在加载
const isLoading = ref(false)

// 输入框引用
const inputRef = ref(null)
const messagesContainer = ref(null)

// 获取用户ID
const getUserId = () => {
  const userInfo = getUserInfo()
  if (userInfo && userInfo.userid) {
    return userInfo.userid
  }
  // 如果没有userid，使用一个默认值或生成一个唯一ID
  return `user_${Date.now()}`
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim()) {
    return
  }

  if (isLoading.value) {
    showToast('正在处理中，请稍候...')
    return
  }

  const question = inputText.value.trim()

  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: question,
    timestamp: new Date().getTime()
  }
  
  messages.value.push(userMessage)
  inputText.value = ''
  inputHeight.value = 48
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })

  // 调用 Coze 接口
  isLoading.value = true
  
  try {
    const token = getAccessToken()
    const userId = getUserId()
    
    const response = await fetch('http://localhost:8000/coze/chat', {
      method: 'POST',
      headers: {
        'Authorization': token ? `Bearer ${token}` : '',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        user_id: userId,
        question: question
      })
    })

    const result = await response.json()
    
    if (result.status === 'success') {
      // 添加 AI 回复消息
      const aiMessage = {
        id: Date.now() + 1,
        type: 'ai',
        content: result.response || '未能生成回答',
        timestamp: new Date().getTime()
      }
      messages.value.push(aiMessage)
    } else {
      showToast(result.detail || '获取回答失败')
      // 添加错误提示消息
      const errorMessage = {
        id: Date.now() + 1,
        type: 'ai',
        content: `抱歉，处理您的问题时出现错误：${result.detail || '未知错误'}`,
        timestamp: new Date().getTime()
      }
      messages.value.push(errorMessage)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    showToast('网络错误，请稍后重试')
    // 添加错误提示消息
    const errorMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: '抱歉，网络连接出现问题，请稍后重试',
      timestamp: new Date().getTime()
    }
    messages.value.push(errorMessage)
  } finally {
    isLoading.value = false
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 输入框高度自适应
const adjustInputHeight = () => {
  if (inputRef.value) {
    inputRef.value.style.height = '48px'
    inputRef.value.style.height = Math.min(inputRef.value.scrollHeight, 120) + 'px'
    inputHeight.value = Math.min(inputRef.value.scrollHeight, 120)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const msgDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
  
  if (msgDate.getTime() === today.getTime()) {
    // 今天显示时间
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    // 其他日期显示日期和时间
    return date.toLocaleString('zh-CN', { 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
}

// 格式化消息时间（用于显示在消息之间）
const shouldShowTime = (currentMsg, prevMsg) => {
  if (!prevMsg) return true
  const timeDiff = currentMsg.timestamp - prevMsg.timestamp
  return timeDiff > 300000 // 5分钟
}

onMounted(() => {
  // 添加欢迎消息
  const welcomeMessage = {
    id: Date.now(),
    type: 'ai',
    content: '您好！我是Coze智能助手，可以帮您解答各种问题。请告诉我您需要什么帮助，我会尽力为您提供准确的信息和建议。',
    timestamp: new Date().getTime()
  }
  messages.value.push(welcomeMessage)
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
})
</script>

<template>
  <div class="coze-chat-page">
    <!-- 顶部导航栏 -->
    <div class="chat-header">
      <div class="header-left" @click="router.back()">
        <span class="back-icon">←</span>
      </div>
      <div class="header-center">
        <div class="service-avatar">💬</div>
        <div class="service-info">
          <div class="service-name">Coze聊天</div>
          <div class="service-status">
            <span class="status-dot online"></span>
            <span class="status-text">在线</span>
          </div>
        </div>
      </div>
      <div class="header-right"></div>
    </div>

    <!-- 消息列表容器 -->
    <div ref="messagesContainer" class="messages-container">
      <!-- 消息列表 -->
      <div class="messages-list">
        <div 
          v-for="(message, index) in messages" 
          :key="message.id"
          class="message-wrapper"
        >
          <!-- 时间戳 -->
          <div v-if="shouldShowTime(message, messages[index - 1])" class="time-divider">
            {{ formatTime(message.timestamp) }}
          </div>

          <!-- 消息气泡 -->
          <div :class="['message-item', message.type]">
            <!-- 头像 -->
            <div class="message-avatar">
              {{ message.type === 'ai' ? '💬' : '👤' }}
            </div>

            <!-- 消息内容 -->
            <div class="message-content">
              <div class="message-bubble" :class="message.type">
                <div class="message-text">{{ message.content }}</div>
                <div v-if="isLoading && message.type === 'user' && index === messages.length - 1" class="typing-indicator">
                  <span></span><span></span><span></span>
                </div>
              </div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-container">
        <!-- 输入框 -->
        <textarea
          ref="inputRef"
          v-model="inputText"
          class="message-input"
          placeholder="请输入您的行程需求..."
          rows="1"
          :disabled="isLoading"
          @input="adjustInputHeight"
          @keydown.enter.exact.prevent="sendMessage"
        ></textarea>

        <!-- 发送按钮 -->
        <button 
          :class="['send-btn', { active: inputText.trim() && !isLoading }]"
          @click="sendMessage"
          :disabled="!inputText.trim() || isLoading"
        >
          <span v-if="inputText.trim() && !isLoading" class="send-text">发送</span>
          <span v-else-if="isLoading" class="send-icon">⏳</span>
          <span v-else class="send-icon">🎤</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.coze-chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
  overflow: hidden;
}

/* 顶部导航栏 */
.chat-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left,
.header-right {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.back-icon {
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.header-center {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: center;
}

.service-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.service-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.service-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.service-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #999;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #52c41a;
  box-shadow: 0 0 6px rgba(82, 196, 26, 0.5);
}

/* 消息容器 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  scroll-behavior: smooth;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 时间分隔线 */
.time-divider {
  text-align: center;
  font-size: 12px;
  color: #999;
  padding: 8px 0;
  position: relative;
}

.time-divider::before,
.time-divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30%;
  height: 1px;
  background: #e8e8e8;
}

.time-divider::before {
  left: 0;
}

.time-divider::after {
  right: 0;
}

/* 消息项 */
.message-wrapper {
  display: flex;
  flex-direction: column;
}

.message-item {
  display: flex;
  gap: 8px;
  max-width: 80%;
  animation: fadeInUp 0.3s ease-out;
}

.message-item.user {
  flex-direction: row-reverse;
  margin-left: auto;
}

.message-item.ai {
  flex-direction: row;
  margin-right: auto;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-item.user .message-content {
  align-items: flex-end;
}

.message-item.ai .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 12px;
  word-wrap: break-word;
  word-break: break-word;
  position: relative;
  max-width: 100%;
}

.message-bubble.ai {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-top-left-radius: 4px;
}

.message-bubble.user {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-top-right-radius: 4px;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  color: inherit;
}

.message-time {
  font-size: 11px;
  color: #999;
  padding: 0 4px;
}

/* 输入区域 */
.input-area {
  background: #fff;
  border-top: 1px solid #e8e8e8;
  padding: 12px 16px;
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  background: #f5f5f5;
  border-radius: 24px;
  padding: 8px 12px;
}

.message-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 14px;
  color: #333;
  resize: none;
  outline: none;
  max-height: 120px;
  min-height: 32px;
  line-height: 1.5;
  padding: 4px 0;
  font-family: inherit;
}

.message-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.message-input::placeholder {
  color: #999;
}

.send-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  transition: all 0.2s;
  font-size: 18px;
  padding: 0;
}

.send-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: auto;
  padding: 0 12px;
  border-radius: 16px;
}

.send-btn.active .send-text {
  font-size: 14px;
  color: #fff;
  font-weight: 500;
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.send-icon {
  font-size: 18px;
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  padding-left: 4px;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.7);
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-10px);
    opacity: 1;
  }
}

/* 动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 4px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 2px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .message-item {
    max-width: 85%;
  }

  .service-avatar {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }

  .service-name {
    font-size: 15px;
  }
}

/* 安全区域适配 */
.input-area {
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
}
</style>


